const db = require("../db")
var date = require("silly-datetime");
const _ = require("lodash")
const today = date.format(new Date(),'YYYY-MM-DD HH:mm:ss'); 

module.exports = {
    getUserCart:(req,res)=>{
        let userId = req.body.id
        db.query("select  user_cart.shopId ,goods.id as id,(user_cart.count * goods.price) as sum,goods_pic.picName as imgSrc,user_cart.count as number ,shop.shopName,goods.goodName as title,goods.keyWord as type,goods.model,goods.price as nowPrice,goods.priceAgo as originalPrice from user_cart,shop,goods,goods_pic where userId = ? and shop.id = user_cart.shopId and goods.id in (user_cart.goodsId) and goods.fileId = goods_pic.id and user_cart.is_delete = 0  ",userId,function(err,result){
            if(err)  return res.cc(err)
            let dataList = _.groupBy(result,'shopName')
            let resultList=[]
            for(item in dataList){
                dataList[item].isChecked = false
                let temp = {
                    'shopName':item,
                    'isChecked':false,
                    'id':dataList[item][0].shopId,
                    items:dataList[item]
                }
                resultList.push(temp)
            }
            res.send({
                code:200,
                msg:"获取购物车列表成功！",
                data:resultList
            })
        })
    },
    delCartItem:(req,res)=>{
        let shopId = req.body.shopId
        let goodId = req.body.goodId
        let userId = req.body.userId
        db.query('update user_cart set is_delete = 1 where userId = ? and shopId = ? and goodsId = ? ',[userId,shopId,goodId],function(err,result){
            if(err) return res.cc(err)
            return res.cc("删除成功！",200)
        })
    },
    // 添加到购物车
    addCartItem:(req,res)=>{
        let goodId = req.body.goodId
        let shopId = req.body.shopId
        let userId = req.body.userId
        db.query("select count from user_cart where userId =? and goodsId = ? and shopId =?",[userId,goodId,shopId],function(err,result){
            if(err) return res.cc(err)
            if(result.length == 0){
                db.query("insert into user_cart(userId,goodsId,shopId,count) values (?,?,?,1)",[userId,goodId,shopId],function(err,result){
                    if(err) return res.cc(err)
                    return res.cc("添加购物车成功！",200)
                })
            }else{
                let count = result[0].count
                count+=1
                db.query("update user_cart set  count = ? where userId =? and goodsId = ? and shopId =?",[count,userId,goodId,shopId],function(err,result){
                    if(err) return res.cc(err)
                    return res.cc("添加购物车成功！",200)
                })
            }
        })
    }
}